package com.book.warehouse.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.business.entity.BookSell;
import com.book.business.service.BookSellService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.BookMethod;
import com.book.common.utils.FebsUtil;
import com.book.shelves.entity.BookStore;
import com.book.shelves.service.BookStoreService;
import com.book.warehouse.entity.WarehouseBook;
import com.book.warehouse.entity.WarehouseHouse;
import com.book.warehouse.entity.WarehouseHouseBook;
import com.book.warehouse.service.WarehouseBookService;
import com.book.warehouse.service.WarehouseHouseBookService;
import com.book.warehouse.service.WarehouseHouseService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.*;

/**
 * @Author: 刘恬镯
 * @Description: 20174052
 */

@Controller
public class WarehouseBookController extends BaseController {
    @Autowired
    WarehouseBookService warehouseBookService;
    @Autowired
    WarehouseHouseService warehouseHouseService;
    @Autowired
    WarehouseHouseBookService warehouseHouseBookService;
    @Autowired
    BookStoreService bookStoreService;
    @Autowired
    BookSellService bookSellService;


    @GetMapping(FebsConstant.VIEW_PREFIX + "warehouse/warehouseBook")
    public String warehouseBookIndex() {
        return FebsUtil.view("warehouse/warehouseBook/warehouseBookList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "warehouse/warehouseBook/in")
    public String warehouseBookInIndex() {
        return FebsUtil.view("warehouse/warehouseBook/warehouseBookNextList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "warehouse/warehouseBook/add")
    public String warehouseBookAdd() {
        return FebsUtil.view("warehouse/warehouseBook/warehouseBookAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "warehouse/warehouseBook/update/{id}")
    public String warehouseBookUpdate(@PathVariable Integer id, ModelMap modelMap) {
        WarehouseBook warehouseBook = this.warehouseBookService.getById(id);
        modelMap.put("warehouseBook", warehouseBook);
        return FebsUtil.view("warehouse/warehouseBookHouse/warehouseBookUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "warehouse/warehouseBook/in/{id}")
    public String bookMessageAsk(@PathVariable Integer id, ModelMap modelMap) {
        WarehouseBook warehouseBook = warehouseBookService.getById(id);
        modelMap.put("warehouseBook", warehouseBook);
        return FebsUtil.view("warehouse/warehouseBook/warehouseBookAsk");
    }

    @GetMapping("warehouseBook")
    @ResponseBody
    @RequiresPermissions("warehouseBook:view")
    public FebsResponse getAllType(WarehouseBook warehouseBook) {
        return new FebsResponse().success().data(this.warehouseBookService.findWarehouseBook(warehouseBook));
    }

    @Log("访问入库信息")
    @GetMapping("warehouseBook/list")
    @ResponseBody
    @RequiresPermissions("warehouseBook:view")
    public FebsResponse warehouseBookIPage(QueryRequest request, WarehouseBook warehouseBook) {
        Map<String, Object> dataTable = getDataTable(this.warehouseBookService.pageWarehouseBook(request, warehouseBook));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("入库-新增")
    @PostMapping("warehouseBook")
    @ResponseBody
    @RequiresPermissions("warehouseBook:add")
    @ControllerEndpoint(operation = "新增入库信息成功", exceptionMessage = "新增入库信息失败")
    public FebsResponse warehouseBookAdd(WarehouseBook warehouseBook) {
        String breId = BookMethod.getUUID();
        QueryWrapper<WarehouseBook> warehouseBookQueryWrapper = new QueryWrapper<>();
        warehouseBookQueryWrapper.eq("bookname", warehouseBook.getBookname()).eq("intoware", "0").eq("status", "1");
        WarehouseBook one = warehouseBookService.getOne(warehouseBookQueryWrapper);
        if (one == null) {
            warehouseBook.setBookid(Integer.valueOf(breId));
            if (warehouseBook.getNumber() >= 100) {
                warehouseBook.setStatus("1").setFlag("0").setIntoware("0").setPutaway("1").setWarningnumber(100);
            } else {
                warehouseBook.setStatus("1").setFlag("0").setIntoware("0").setPutaway("0").setWarningnumber(100);
            }
            this.warehouseBookService.addWarehouseBook(warehouseBook);
        } else {
            one.setNumber(one.getNumber() + warehouseBook.getNumber());
            this.warehouseBookService.updateWarehouseBook(warehouseBook);
        }
        return new FebsResponse().success();
    }

    @Log("入库-预警")
    @PostMapping("warehouseBook/update")
    @ResponseBody
    @RequiresPermissions("warehouseBook:update")
    @ControllerEndpoint(operation = "修改入库信息成功", exceptionMessage = "修改入库信息失败")
    public FebsResponse warehouseBookUpdate(WarehouseBook warehouseBook) {
        WarehouseBook byId = warehouseBookService.getById(warehouseBook.getWarehouseid());
        byId.setWarningnumber(warehouseBook.getWarningnumber());
        if (byId.getNumber() >= warehouseBook.getWarningnumber()) {
            byId.setWarningstatus("0");
        }
        if (byId.getNumber() < warehouseBook.getWarningnumber()) {
            byId.setWarningstatus("1");
        }
        warehouseBookService.updateWarehouseBook(byId);
        return new FebsResponse().success();
    }

    @Log("入库-删除")
    @PostMapping("warehouseBook/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("warehouseBook:delete")
    @ControllerEndpoint(operation = "删除入库信息成功", exceptionMessage = "删除入库信息失败")
    public FebsResponse warehouseBookdelete(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<WarehouseBook> warehouseBooks = (List<WarehouseBook>) warehouseBookService.listByIds(Arrays.asList(attr));
        for (int i = 0; i < warehouseBooks.size(); i++) {
            if ("1".equals(warehouseBooks.get(i).getPutaway())) {
                return new FebsResponse().message("该书籍已经上架不能删除！");
            }
            warehouseHouseBookService.remove(new QueryWrapper<WarehouseHouseBook>().lambda()
                    .eq(WarehouseHouseBook::getBookid, warehouseBooks.get(i).getBookid()));
        }
        this.warehouseBookService.deleteWarehouseBook(attr);
        return new FebsResponse().success();
    }

    @Log("入库-审批")
    @PostMapping("warehouseBook/yes/{ids}")
    @ResponseBody
    @RequiresPermissions("warehouseBook:yes")
    @ControllerEndpoint(operation = "审批入库信息成功", exceptionMessage = "审批入库信息失败")
    public FebsResponse warehouseBookyes(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<WarehouseBook> warehouseBookList = warehouseBookService.askWarehouseBook(attr);
        for (int i = 0; i < warehouseBookList.size(); i++) {
            if ("1".equals(warehouseBookList.get(i).getFlag()) || "2".equals(warehouseBookList.get(i).getFlag())) {
                return new FebsResponse().message("不能重复审核！");
            }
            WarehouseBook warehouseBookServiceOne = warehouseBookService.getOne(new QueryWrapper<WarehouseBook>().lambda()
                    .eq(WarehouseBook::getBookname, warehouseBookList.get(i).getBookname())
                    .eq(WarehouseBook::getPutaway, "1"));
            if (warehouseBookServiceOne != null) {
                BookStore bookStore = bookStoreService.getOne(new QueryWrapper<BookStore>().lambda().notIn(BookStore::getFlag, "1")
                        .eq(BookStore::getBookname, warehouseBookList.get(i).getBookname()));
                BookSell bookSell = bookSellService.getOne(new QueryWrapper<BookSell>().lambda().eq(BookSell::getBookname, warehouseBookList.get(i).getBookname()));
                bookStore.setNum(bookStore.getNum() + warehouseBookList.get(i).getNumber());
                if (bookStore.getNum() + warehouseBookList.get(i).getNumber() >= bookStore.getWarningnumber()) {
                    bookStore.setFlag("0");
                } else {
                    bookStore.setFlag("2");
                }
                bookSell.setNumber(bookSell.getNumber() + warehouseBookList.get(i).getNumber());
                bookSellService.updateBookSell(bookSell);
                bookStoreService.updateBookStore(bookStore);
            }
            warehouseBookList.get(i).setFlag("1").setIntoware("0");
            warehouseBookService.updateWarehouseBook(warehouseBookList.get(i));
        }
        return new FebsResponse().success();
    }

    @Log("入库-驳回")
    @PostMapping("warehouseBook/no/{ids}")
    @ResponseBody
    @RequiresPermissions("warehouseBook:no")
    @ControllerEndpoint(operation = "驳回入库信息成功", exceptionMessage = "驳回入库信息失败")
    public FebsResponse warehouseBookno(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<WarehouseBook> warehouseBookList = warehouseBookService.askWarehouseBook(attr);
        for (int i = 0; i < warehouseBookList.size(); i++) {
            warehouseBookList.get(i).setFlag("2");
            warehouseBookService.updateWarehouseBook(warehouseBookList.get(i));
        }
        return new FebsResponse().success();
    }

    @Log("入库分配")
    @PostMapping("warehouseBook/in")
    @ResponseBody
    @RequiresPermissions("warehouseBook:in")
    public FebsResponse warehouseBookIn(@Valid WarehouseBook warehouseBook) {
        WarehouseHouse warehouseHouse = warehouseHouseService.getById(warehouseBook.getHouseid());
        if (warehouseBook.getNumber() == 0) {
            return new FebsResponse().message("请核实入库书籍数量");
        }
        if (warehouseBook.getNumber() > warehouseHouse.getHousenumber() - warehouseHouse.getHousebooks()) {
            return new FebsResponse().message("该仓库库存不足，请重新选择仓库！");
        }
        //更新已添加到仓库的书籍
        WarehouseBook warehouseBookServiceOne = warehouseBookService.getOne(new QueryWrapper<WarehouseBook>().lambda()
                .eq(WarehouseBook::getIntoware, "1").eq(WarehouseBook::getBookname, warehouseBook.getBookname()));
        if (warehouseBookServiceOne == null) {
            warehouseBook.setWarningnumber(100);
            if (warehouseBook.getNumber() >= 100) {
                warehouseBook.setWarningstatus("0");
            } else {
                warehouseBook.setWarningstatus("1");
            }
            warehouseBook.setIntoware("1");
            warehouseBookService.updateWarehouseBook(warehouseBook);
            //添加到多表联查,由于bookid唯一，warehouse_house_book表其仓库对应的书籍唯一，这里直接添加
            WarehouseHouseBook warehouseHouseBook = new WarehouseHouseBook()
                    .setBookid(warehouseBook.getBookid())
                    .setHouseid(warehouseBook.getHouseid())
                    .setHbnumber(warehouseBook.getNumber());
            warehouseHouseBookService.addWarehouseHouseBook(warehouseHouseBook);
        } else {
            if (warehouseBookServiceOne.getNumber() + warehouseBook.getNumber() >= warehouseBookServiceOne.getWarningnumber()) {
                warehouseBook.setWarningstatus("0");
            } else {
                warehouseBook.setWarningstatus("1");
            }
            warehouseBookServiceOne.setNumber(warehouseBookServiceOne.getNumber() + warehouseBook.getNumber());
            warehouseBookService.updateWarehouseBook(warehouseBookServiceOne);
            warehouseBookService.removeById(warehouseBook.getWarehouseid());
            //添加到多表联查,由于要区分各仓库拥有的书籍，这里复用原有的唯一bookid
            WarehouseHouseBook warehouseHouseBook = new WarehouseHouseBook()
                    .setBookid(warehouseBookServiceOne.getBookid())
                    .setHouseid(warehouseBook.getHouseid())
                    .setHbnumber(warehouseBook.getNumber());
            warehouseHouseBookService.addWarehouseHouseBook(warehouseHouseBook);
        }
        //更新仓库书籍数量
        warehouseHouse.setHousebooks(warehouseHouse.getHousebooks() + warehouseBook.getNumber());
        warehouseHouseService.updateWarehouseHouse(warehouseHouse);
        return new FebsResponse().success();
    }
}
